package com.zrgj.front.controller;

import com.alibaba.dubbo.common.json.JSON;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.zrgj.common.response.BaseResponse;
import com.zrgj.common.response.StatusCodeEnum;
import com.zrgj.domain.*;
import com.zrgj.front.config.AlipayConfig;
import com.zrgj.manager.service.IOrderService;
import com.zrgj.manager.service.IProductService;
import com.zrgj.manager.service.IShoppingCarService;
import com.zrgj.manager.service.IUserService;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping(value = "/order")
public class OrderController {
    @Reference
    private IShoppingCarService shoppingCarService;
    @Reference
    private IUserService userService;
    @Reference
    private IOrderService orderService;
    @Reference
    private IProductService productService;

    @RequestMapping(value = "/setOrder")
    public BaseResponse setOrder(Integer carId, HttpServletResponse response) {
        Cookie cookie = new Cookie("CARTID",carId.toString());
        cookie.setPath("/");
        cookie.setMaxAge(1800);
        response.addCookie(cookie);

        return new BaseResponse(StatusCodeEnum.SUCCESS,"user_create_order");
    }

    /**
     * 生成订单页面
     * @param cartId
     * @return
     */
    @RequestMapping(value = "/getOrder")
    public BaseResponse getOrder(Integer cartId){
        ShoppingCar shoppingCar = shoppingCarService.selectByCartId(cartId);
        return new BaseResponse(StatusCodeEnum.SUCCESS,shoppingCar);
    }

    /**
     * 跳转到订单页面
     * @param userName
     * @return
     */
    @RequestMapping(value = "/toOrder")
    public BaseResponse toOrder(String userName){
        User user = userService.findByName(userName);
        if (user == null){
            return new BaseResponse(StatusCodeEnum.NOT_LOGIN,"user_loginUI");
        }

        return new BaseResponse(StatusCodeEnum.SUCCESS,"user_order");
    }

    /**
     * 获取当前用户订单列表
     * @param userName
     * @return
     */
    @RequestMapping(value = "/getOrderList")
    public BaseResponse getOrderList(String userName){
        User user = userService.findByName(userName);
        if (user == null){
            return new BaseResponse(StatusCodeEnum.NOT_LOGIN,"user_loginUI");
        }
        List<Order> orderList = orderService.selectAll(user.getUserId());

        return new BaseResponse(StatusCodeEnum.SUCCESS,orderList);
    }

    /**
     * 生成订单
     * @param orderShop
     * @return
     */
    @RequestMapping(value = "/createOrder")
    public BaseResponse createOrder(@RequestBody OrderShop orderShop, HttpServletResponse response){
        ShoppingCar cart = shoppingCarService.selectByCartId(orderShop.getCarId());
        User user = userService.findByName(orderShop.getUserName());

        Order order = orderShop.getOrder();

        ArrayList<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = new OrderItem();

        orderItem.setProductPo(cart.getProductPo());
        orderItem.setTotal(cart.getCarCount());
        orderItem.setOrderCount(cart.getCarCount() * cart.getProductPo().getProductPrice());
        orderItem.setProductId(cart.getProductId());
        orderItems.add(orderItem);

        order.setOrderAmount(cart.getCarCount() * cart.getProductPo().getProductPrice());
        order.setOrderItems(orderItems);
        order.setUserId(user.getUserId());

        String insert = orderService.insert(order);
        shoppingCarService.delete(orderShop.getCarId());

        Cookie cookie = new Cookie("ORDER", insert);
        cookie.setMaxAge(1800);
        cookie.setPath("/");
        response.addCookie(cookie);

        return new BaseResponse(StatusCodeEnum.SUCCESS);
    }

    /**
     * 删除订单
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/deleteOrder")
    public BaseResponse deleteOrder(String orderId){
        orderService.delete(orderId);
        return new BaseResponse(StatusCodeEnum.SUCCESS);
    }

    /**
     * 确认收货
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/sure")
    public BaseResponse sure(String orderId){
        Order order = orderService.findById(orderId);
        order.setStateId(4);
        orderService.update(order);
        return new BaseResponse(StatusCodeEnum.SUCCESS);
    }

    /**
     * 评价
     * @param orderId
     * @param response
     * @return
     */
    @RequestMapping(value = "/comment")
    public BaseResponse comment(String orderId,HttpServletResponse response){
        Order order = orderService.findById(orderId);
        order.setStateId(5);
        orderService.update(order);

        Cookie cookie = new Cookie("PRODUCT",order.getOrderItems().get(0).getProductPo().getProductId().toString());
        cookie.setPath("/");
        cookie.setMaxAge(1800);
        response.addCookie(cookie);

        return new BaseResponse(StatusCodeEnum.SUCCESS);
    }

    /**
     * 支付
     * @param orderId
     * @return
     */
    @PostMapping("/AliPay")
    public String goPay(String orderId){
        Order order = orderService.findById(orderId);
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        Date date = new Date();
        String out_trade_no = Long.toString(date.getTime());
        //付款金额，必填
        String total_amount = String.valueOf(order.getOrderAmount());
        //订单名称，必填
        String subject = order.getOrderItems().get(0).getProductPo().getProductName();
        //商品描述，可空
        String body = order.getOrderItems().get(0).getProductPo().getProductInfoIntroduction();
        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "1c";
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        try {
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            order.setStateId(2);
            orderService.update(order);
            return result;
        }catch (Exception e){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status",500);
            return "fail";
        }


    }


}
